import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './router'
import store from './store'
import { asyncRouter } from '@/router/index'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      // 判断是否获取过资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // console.log(roles.menus)
        // console.log(asyncRouter)
        const filterRoutes = asyncRouter.filter(item => {
          return roles.menus.includes(item.name)
        })
        // console.log(filterRoutes)
        // 筛选后的路由
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 让路由拥有信息(router的已知缺陷)
        next(to.path)
      } else {
        // 放过
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})

router.afterEach(() => {
  nProgress.done()
})
